package com.tuomaxu.filter;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@Component
@RefreshScope
public class IPDefFilter implements GlobalFilter, Ordered {

    @Data
    private class RegisterInfo{
        private String ip;
        private Date date;
    }

    //x分钟内
    @Value("${IPDef.x}")
    private int x;

    //y次
    @Value("${IPDef.y}")
    private int y;

    private ArrayList<RegisterInfo> registers = new ArrayList();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        RequestPath path = request.getPath();
        System.out.println(path);
        String s = path.toString();
        String[] split = s.split("/");
        if(split[1].equals("user") && split[2].equals("register")){
            String ip = request.getRemoteAddress().getHostString();
            Date now = new Date();
            long time = now.getTime();
            int count = 0;
            //查询此ip的x分内的注册数量
            for (RegisterInfo register : registers) {
                if(register.getIp().equals(ip)){
                    long time1 = register.getDate().getTime();
                    if((time - time1)< x*1000*60){
                        count++;
                    }
                }
            }
            if(count>=y){
                response.setStatusCode(HttpStatus.FORBIDDEN);
                String data = "您频繁进⾏注册，请求已被拒绝!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            RegisterInfo registerInfo = new RegisterInfo();
            registerInfo.setIp(ip);
            registerInfo.setDate(new Date());
            registers.add(registerInfo);
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
